package com.jiao.Handler.Security;

import com.jiao.domain.Result;
import com.jiao.enums.ExceptionCodeEnum;
import com.jiao.utils.WebUtils;
import com.alibaba.fastjson.JSON;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/*
* 而这个处理器，就是为了在认证时，只要出现报错，那么就会转到AuthenticationEntryPoint#commence方法进行异常处理
* 与系统内部报错，区分开来
* */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {

        authException.printStackTrace();
        //InsufficientAuthenticationException
        //BadCredentialsException
        Result<String> result;
        if(authException instanceof BadCredentialsException){
            result = Result.error(ExceptionCodeEnum.USERNAME_ERROR);
        }else if(authException instanceof InsufficientAuthenticationException){
            result = Result.error(ExceptionCodeEnum.NEED_LOGIN);
        }else{
            result = Result.error(ExceptionCodeEnum.LOGIN_ERROR);
        }
        String json = JSON.toJSONString(result);
        //传输给前端
        WebUtils.renderString(response,json);
    }
}